//
//  WeiboView.m
//  BookRank
//
//  Created by wststar on 13-10-31.
//  Copyright (c) 2013年 wststar. All rights reserved.
//

#import "WeiboView.h"
#import "UIFactory.h"
#import "WeiboModel.h"
#import "RTLabel.h"
#import "UIImageView+WebCache.h"
#import "ThemeImageView.h"
#import "RegexKitLite.h"
#import "NSString+URLEncoding.h"

#define LIST_FONT   14.0f           //列表中文本字体
#define LIST_REPOST_FONT  13.0f;    //列表中转发的文本字体
#define DETAIL_FONT  18.0f          //详情的文本字体
#define DETAIL_REPOST_FONT 17.0f    //详情中转发的文本字体

@implementation WeiboView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self _initView];
        parseText = [[NSMutableString alloc]init];
    }
    return self;
}

-(void)_initView{
    //内容
    _textLabel =[[RTLabel alloc]initWithFrame:CGRectZero];
    _textLabel.delegate = self;
    _textLabel.font = [UIFont systemFontOfSize:14];
    // r:69 g:149 b:203 转换成16进制 #4595CB
    [_textLabel setLinkAttributes:[NSDictionary dictionaryWithObject:@"#4595CB" forKey:@"color"]];
    [_textLabel setSelectedLinkAttributes:[NSDictionary dictionaryWithObject:@"darkGray" forKey:@"color"]];
    [self addSubview:_textLabel];
    
    //图片
    _image = [[UIImageView alloc]initWithFrame:CGRectZero];
    [_image setImage:[UIImage imageNamed:@"page_image_loading.png"]];
    [self addSubview:_image];
    
    //转发微博背景视图
    _repostBackgroundView =[UIFactory createImageView:@"timeline_retweet_background.png"];
    UIImage * image = [_repostBackgroundView.image stretchableImageWithLeftCapWidth:25 topCapHeight:10];
    _repostBackgroundView.image = image;
    _repostBackgroundView.leftCapWidth = 25;
    _repostBackgroundView.topCapHeight = 10;
    //[image release];
    [_repostBackgroundView setBackgroundColor: [UIColor clearColor] ];
    [self insertSubview:_repostBackgroundView atIndex:0];
}

-(void)setWeiboModel:(WeiboModel *)weiboModel{
    if (_weiboModel != weiboModel) {
        [_weiboModel release];
        _weiboModel = [weiboModel retain];
    }
    //创建转发微博视图
    if (_repostView == nil) {
        _repostView = [[WeiboView alloc]initWithFrame:CGRectZero];
        _repostView.isRepost = YES;
        [self addSubview:_repostView];
    }
    
    [self parseLink];
}

//解析超链接
-(void)parseLink{
    [parseText setString:@""];
    
    //判断是否转发微博 添加原微博作者名字
    if (_isRepost) {
        NSString * nick = _weiboModel.user.screen_name;
        [ parseText appendFormat:@"<a href='user://%@'>%@</a>: ",[nick URLEncodedString],nick];
    }
    
    NSString * text = self.weiboModel.text;
    NSString * regex = @"(@\\w+)|(#\\w+#)|(http(s)?://([A-za-z0-9._-]+(/)?)*)";
    NSArray * matchArray = [text componentsMatchedByRegex:regex];
    for (NSString * linkString in matchArray) {
        NSString * reples = @"";
        if ([linkString hasPrefix:@"@"]) {
            reples = [NSString stringWithFormat:@"<a href='user://%@'>%@</a>",[linkString URLEncodedString],linkString];
        }else if([linkString hasPrefix:@"http"]) {
            reples = [NSString stringWithFormat:@"<a href='%@'>%@</a>",linkString,linkString];
        }else if([linkString hasPrefix:@"#"]) {
            reples = [NSString stringWithFormat:@"<a href='topic://%@'>%@</a>",[linkString URLEncodedString],linkString];
        }
        if (reples != nil) {
           text = [text stringByReplacingOccurrencesOfString:linkString withString:reples];
        }
    }
    [parseText appendString:text];
}


#pragma mark --展示数据 设置布局
-(void)layoutSubviews{
    [super layoutSubviews];
    
    //微博内容 textLabel 子视图
    //获取字体大小
    float fontSize = [WeiboView getFontSize:self.isDetail isRepost:self.isRepost];
    _textLabel.font = [UIFont systemFontOfSize:fontSize];
    _textLabel.frame = CGRectMake(0, 0, self.width, 20);
    if (self.isRepost) {
        _textLabel.frame = CGRectMake(10, 10, self.width-20, 0);
    }
    _textLabel.text = parseText;
    //文本内容尺寸
    CGSize textSize = _textLabel.optimumSize;
    _textLabel.height = textSize.height;
    
    //微博内容 转发视图
    WeiboModel * repostWeibo = _weiboModel.relWeibo;
    if (repostWeibo != nil) {
        _repostView.weiboModel = repostWeibo;
        //计算转发微博视图的高度
        float height = [WeiboView getWeiboViewHeight:repostWeibo isRepost:YES isDetail:self.isDetail];
        _repostView.frame = CGRectMake(0, _textLabel.bottom, self.width, height);
        _repostView.hidden = NO;
    }else{
        _repostView.hidden = YES;
    }
    
    //微博图片视图
    if (self.isDetail) {
        //中等图
        NSString * bmiddleImage = _weiboModel.bmiddleImage;
        if (bmiddleImage != nil && ![@"" isEqualToString:bmiddleImage]) {
            _image.hidden = NO;
            _image.frame = CGRectMake(10, _textLabel.bottom, 280, 200);
            //加载网络图片数据
            [_image setImageWithURL:[NSURL URLWithString:bmiddleImage]];
        }else{
            _image.hidden = YES;
        }
    }else{
        //缩略图
        NSString * thumbnailImage = _weiboModel.thumbnailImage;
        if (thumbnailImage != nil && ![@"" isEqualToString:thumbnailImage]) {
            _image.hidden = NO;
            _image.frame = CGRectMake(10, _textLabel.bottom, 70, 80);
            //加载网络图片数据
            [_image setImageWithURL:[NSURL URLWithString:thumbnailImage]];
        }else{
            _image.hidden = YES;
        }
    }
    
    //转发微博视图背景
    if (self.isRepost) {
        _repostBackgroundView.frame = self.bounds;
        _repostBackgroundView.hidden = NO;
    } else {
        _repostBackgroundView.hidden = YES;
    }
    
    
}

#pragma mark - 计算
+ (float)getFontSize:(BOOL)isDetail isRepost:(BOOL)isRepost{
    float fontSize = 14.0f;
    
    if (!isDetail && !isRepost) {
        return LIST_FONT;
    }
    else if(!isDetail && isRepost) {
        return LIST_REPOST_FONT;
    }
    else if(isDetail && !isRepost) {
        return DETAIL_FONT;
    }
    else if(isDetail && isRepost) {
        return DETAIL_REPOST_FONT;
    }
    return fontSize;
}

//计数微博视图的高度
+ (CGFloat)getWeiboViewHeight:(WeiboModel *)weiboModel
                     isRepost:(BOOL)isRepost
                     isDetail:(BOOL)isDetail {
    /**
     * 实现思路：计算每个子视图的高度，然后相加。
     **/
    float height = 0;
    //--------------------计算微博内容text的高度------------------------
    RTLabel *textLabel = [[[RTLabel alloc] initWithFrame:CGRectZero]autorelease];
    float fontsize = [WeiboView getFontSize:isDetail isRepost:isRepost];
    textLabel.font = [UIFont systemFontOfSize:fontsize];
    //判断此微博是否显示在详情页面
    if (isDetail) {
        textLabel.width = kWeibo_Width_Detail;
    } else {
        textLabel.width = kWeibo_Width_List;
    }
    if (isRepost) {
        textLabel.width -= 20;
    }
    
    textLabel.text = weiboModel.text;
    
    height += textLabel.optimumSize.height;
    
    //--------------------计算微博图片的高度------------------------
    if (isDetail) {
        NSString *bmiddleImage = weiboModel.bmiddleImage;
        if (bmiddleImage != nil && ![@"" isEqualToString:bmiddleImage]) {
            height += (200+10);
        }
    }else{
        NSString *thumbnailImage = weiboModel.thumbnailImage;
        if (thumbnailImage != nil && ![@"" isEqualToString:thumbnailImage]) {
            height += (80+10);
        }
    }
    
    
    //--------------------计算转发微博视图的高度------------------------
    //转发的微博
    WeiboModel *relWeibo = weiboModel.relWeibo;
    if (relWeibo != nil) {
        //转发微博视图的高度
        float repostHeight = [WeiboView getWeiboViewHeight:relWeibo isRepost:YES isDetail:isDetail];
        height += (repostHeight);
    }
    
    if (isRepost == YES) {
        height += 30;
    }

    return height;
}


#pragma mark ---RTLabelDelegate
- (void)rtLabel:(id)rtLabel didSelectLinkWithURL:(NSURL*)url{
    NSString * absoluteString = [url absoluteString];
    if ([absoluteString hasPrefix:@"user"]) {
        NSLog(@"用户:%@",[[url host] URLDecodedString]);
    }else if([absoluteString hasPrefix:@"http"]){
        NSLog(@"链接:%@",absoluteString);
    }else if([absoluteString hasPrefix:@"topic"]){
        NSLog(@"话题:%@",[[url host] URLDecodedString]);
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
